package com.pilot.game.web.rest;

import com.codahale.metrics.annotation.Timed;
import com.pilot.game.domain.Agency;
import com.pilot.game.domain.Customer;
import com.pilot.game.service.AgencyService;
import com.pilot.game.service.CustomerService;
import com.pilot.game.service.SmsServices;
import com.pilot.game.web.rest.errors.BadRequestAlertException;
import com.pilot.game.web.rest.util.HeaderUtil;
import com.pilot.game.web.rest.util.PaginationUtil;
import com.pilot.game.web.rest.vm.CommonResponse;
import io.github.jhipster.web.util.ResponseUtil;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

/**
 * REST controller for managing Customer.
 */
@RestController
@RequestMapping("/api")
public class CustomerResource {

    private final Logger log = LoggerFactory.getLogger(CustomerResource.class);

    private static final String ENTITY_NAME = "customer";

    private final CustomerService customerService;
    private final AgencyService agencyService;
    private final CacheManager cacheManager;
    private final SmsServices smsServices;

    public CustomerResource(CustomerService customerService, AgencyService agencyService, CacheManager cacheManager, SmsServices smsServices) {
        this.customerService = customerService;
        this.agencyService = agencyService;
        this.cacheManager = cacheManager;
        this.smsServices = smsServices;
    }

    /**
     * POST  /customers : Create a new customer.
     *
     * @param customer the customer to create
     * @return the ResponseEntity with status 201 (Created) and with body the new customer, or with status 400 (Bad Request) if the customer has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/customers")
    @Timed
    public ResponseEntity<Customer> createCustomer(@Valid @RequestBody Customer customer) throws URISyntaxException {
        log.debug("REST request to save Customer : {}", customer);
        if (customer.getId() != null) {
            throw new BadRequestAlertException("A new customer cannot already have an ID", ENTITY_NAME, "idexists");
        }
        //验证码不匹配
        if (StringUtils.isNotBlank(customer.getCode())) {
            if (!customer.getCode().equals(cacheManager.getCache("SMS").get(customer.getQq(), String.class))) {
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
            }
        }
        if(StringUtils.isNotBlank(customer.getAgency())) {
            Agency agency = agencyService.findByName(customer.getAgency());
            int sumAgencyByFather = agencyService.findSumAgencyByFather(agency.getAccountName());
            int countCustomer = customerService.findCountByAgency(agency.getAccountName());
            if (agency.getLimit() <= (sumAgencyByFather + countCustomer)) {
                throw new BadRequestAlertException("你可创建客户数量为0", ENTITY_NAME, "idexists");
            }
        } else {
            customer.setAgency("官网手机注册");
        }

        List<Customer> customers = customerService.findByAccountName(customer.getAccountName());
        if (!CollectionUtils.isEmpty(customers)) {
            throw new BadRequestAlertException("客户名已存在", ENTITY_NAME, "idexists");
        }

        {
            customer.setOnline(1);
            customer.setDeadline(LocalDate.now().plusDays(2));
        }
        Customer result = customerService.save(customer);
        return ResponseEntity.created(new URI("/api/customers/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    /**
     * POST  /customers／login : customer login
     *
     * @param customer the customer to login
     * @return the ResponseEntity with status 201 (Created) and with body the new customer, or with status 400 (Bad Request) if the customer has already an ID
     */
    @PostMapping("/customers/login")
    @Timed
    public ResponseEntity<Customer> customerLogin(@RequestBody Customer customer) {
        log.debug("REST request to login Customer : {}", customer);
        Customer result = customerService.findByNameAndPwd(customer.getAccountName(), customer.getPassword());
        if (result == null) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }

        if(result.getDeadline().isBefore(LocalDate.now())){
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
        return ResponseEntity.ok(result);
    }

    /**
     * POST  /customers／smsLogin : customer sms login
     *
     * @param mobile the mobile to login
     * @return the ResponseEntity with status 201 (Created) and with body the new customer, or with status 400 (Bad Request) if the customer has already an ID
     */
    @GetMapping("/customers/smsLogin")
    @Timed
    public ResponseEntity<Customer> customerSMSLogin(@RequestParam("mobile") String mobile, @RequestParam("code") String code) {
        log.debug("REST request to login mobile : {}", mobile);
        if(!code.equals(cacheManager.getCache("SMS").get(mobile,String.class))){
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
        Customer result = customerService.findByMobile(mobile);
        if (result == null) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }

        if (result.getDeadline().isBefore(LocalDate.now())) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
        return ResponseEntity.ok(result);
    }

    /**
     * get  /customers／checkCustomer : sendCode
     *
     * @param mobile the mobile to checkCustomer
     * @return the ResponseEntity with status 201 (Created) and with body the new customer, or with status 400 (Bad Request) if the customer has already an ID
     */
    @GetMapping("/customers/checkCustomer")
    @Timed
    public ResponseEntity<Customer> checkCustomer(@RequestParam("mobile") String mobile) {
        log.debug("REST request to checkCustomer mobile : {}", mobile);
        Customer result = customerService.findByMobile(mobile);
        if (result == null) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }

        if (result.getDeadline().isBefore(LocalDate.now())) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
        smsServices.sendSmsMsg(mobile);

        return ResponseEntity.ok(result);
    }

    /**
     * PUT  /customers : Updates an existing customer.
     *
     * @param customer the customer to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated customer,
     * or with status 400 (Bad Request) if the customer is not valid,
     * or with status 500 (Internal Server Error) if the customer couldn't be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/customers")
    @Timed
    public ResponseEntity<Customer> updateCustomer(@Valid @RequestBody Customer customer) throws URISyntaxException {
        log.debug("REST request to update Customer : {}", customer);
        if (customer.getId() == null) {
            return createCustomer(customer);
        }
        Customer result = customerService.save(customer);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, customer.getId().toString()))
            .body(result);
    }

    /**
     * GET  /customers : get all the customers.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of customers in body
     */
    @GetMapping("/customers")
    @Timed
    public ResponseEntity<List<Customer>> getAllCustomers(@ApiParam Pageable pageable, @ApiParam String agencyName) {
        log.debug("REST request to get a page of Customers");
        Customer customer = new Customer();
        customer.setAgency(agencyName);
        Example<Customer> example = Example.of(customer);
        Page<Customer> page = customerService.findAll(example, pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/customers");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

    /**
     * GET  /customers/:id : get the "id" customer.
     *
     * @param id the id of the customer to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the customer, or with status 404 (Not Found)
     */
    @GetMapping("/customers/{id}")
    @Timed
    public ResponseEntity<Customer> getCustomer(@PathVariable Long id) {
        log.debug("REST request to get Customer : {}", id);
        Customer customer = customerService.findOne(id);
        return ResponseUtil.wrapOrNotFound(Optional.ofNullable(customer));
    }

    /**
     * DELETE  /customers/:id : delete the "id" customer.
     *
     * @param id the id of the customer to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/customers/{id}")
    @Timed
    public ResponseEntity<CommonResponse> deleteCustomer(@PathVariable Long id) {
        log.debug("REST request to delete Customer : {}", id);
        customerService.delete(id);
        return new ResponseEntity<>(new CommonResponse("SUCCESS", true), HttpStatus.OK);
    }
}
